package com.interceptor;

import com.model._do.login_do.LoginStatusDO;
import com.service.UserAccessService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

public class AccessInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private UserAccessService userAccessService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        try {
            Map<String, String[]> paramMap = request.getParameterMap();
            String customCode = paramMap.get("customCode")[0];
            if (StringUtils.isEmpty(customCode)) {
                throw new Exception("customCode has no param");
            }
            LoginStatusDO status = userAccessService.getByCustomCode(customCode);
            if (status != null) {
                Date now = new Date();
                if (now.compareTo(status.getGmtLimit()) > 0) {
                    throw new Exception(customCode + " token over time limit");
                }
            } else {
                throw new Exception(customCode + " token not exist");
            }

        } catch (Exception e) {
            response.sendRedirect("/error/common");
            return false;
        }
        return true;
    }
}
